<template>
  <div class="richText">
    <Toolbar
      class="toolbar"
      :editor="editorRef"
      ref="toolbar"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      :style="{ height: height + 'px' }"
      class="editor"
      v-model="copyValue"
      :defaultConfig="{
        placeholder,
        readOnly: disabled
      }"
      :mode="mode"
      @onCreated="handleCreated"
      @keyup="f"
    />
  </div>
</template>

<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css'; // 引入 css

import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
const f = (e) => {
  console.log(e);
};
const props = withDefaults(
  defineProps<{
    mode?: 'simple' | 'default';
    value: any;
    toolbarConfig?: any;
    placeholder?: string;
    height?: number;
    disabled?: boolean;
  }>(),
  {
    mode: 'default',
    toolbarConfig: {
      excludeKeys: ['fullScreen', 'group-video', 'group-image']
    },
    placeholder: '请输入内容...',
    height: 350,
    disabled: false
  }
);

const emit = defineEmits(['update:value']);
const copyValue = computed({
  get() {
    return props.value;
  },
  set(val) {
    emit('update:value', val);
  }
});

const editorRef = shallowRef();
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const toolbar = ref();
const handleCreated = (editor: any) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
defineExpose({ editorRef });
</script>

<style scoped lang="less">
.richText {
  border: 1px solid #ccc;
  .toolbar {
    border-bottom: 1px solid #ccc;
  }
  .editor {
    overflow-y: hidden;
  }
}
</style>
